<script setup lang="ts">
  import { ref, watch } from "vue";
  import order from "@/router/order";
  import { ElTable } from "element-plus";
  import Dialog from "@/components/order/Dialog.vue";
  import { Filter } from "@/components/SideBar";
  type ElTableProps = CPN<typeof ElTable>;
  interface Props extends /* @vue-ignore */ ElTableProps {
    type: orderTypes;
  }
  type orderChild = (typeof order)["children"][number];
  type orderTypes = orderChild["meta"]["title"];

  const fd: gt.components.SideBar.Filter[] = [
    {
      value: "新增", type: "button", opt: { onClick() { click(0); }, type: "primary", class: "mac-ico-add-round", disabled: false }
    },
    { // @ts-ignore
      value: false, type: "switch", onChange() {
        console.log(123);
        redress.value = this.value;
        page.value.current = 1;
        init();
      }, label: "显示红冲", opt: {
        style: "--el-switch-on-color:var(--color-red)", get disabled() {
          return !api.me.per(`${props.type}红冲` as any);
        }
      }
    },
  ],
    props = withDefaults(defineProps<Props>(), {
      type: "消费单"
    }),
    filterData = ref<any>(fd),
    entity = ref<InstanceType<typeof Dialog>>(),
    page = ref<gt.PageData<gt.sql.orderStock>>({ current: 1, size: 10, total: 0, data: [] }),
    redress = ref(false),
    tip = ref([
      { label: `查看`, value: 2, cls: "mac-ico-search", per: true },
      // { label: `红冲`, value: 3, cls: "mac-ico-delete", per: `${props.type}红冲` },
    ] as const);
  async function init() {
    const qr: R<gt.sql.orderStock>[] = [];
    let b = !api.me.per(`${props.type}创建` as any);
    // if (b) {
    //   const r = arrFind(await gd.groupTree, { id: api.me.gid }, "id");
    //   b = props.type == "消费单" || !(r && r[0] == "1");
    // }
    filterData.value[0].opt.disabled = b;
    tip.value.forEach(e => {
      if (typeof e.per == "string") {
        // @ts-ignore
        e.per = api.me.per(e.per);
      }
    });
    if (redress.value) {
      qr.push({ field: "type", logic: "like", value: "%" + props.type });
    } else {
      qr.push({ field: "type", logic: "=", value: props.type });
      if (props.type != "消费单") {
        qr.push({ field: "redress", logic: "=", value: "" });
      }
    }
    const res = await gd.orderStock.read({
      "#page": { current: page.value.current, size: page.value.size },
      "#rule": qr,
      "#orderStock": [["createTime", "DESC"]]
    });
    page.value = res;
  }
  watch(() => props, init, { deep: true, immediate: true });
  async function click(type: number, p?: gt.sql.orderStock) {
    if (!p) {
      p = format.def.orderStock;
    }
    // @ts-ignore
    if (type == 4) {
      ElMessageBox({
        title: "是否确定写入库存？",
        message: "重复点击不会重复写入库存",
      }).then(async () => {
        const r = await api.request({ id: p.id }, "orderConfirm");
        if (r) {
          init();
        }
      }).catch(() => { });
      return;
    } else if (type == 5) { // 确认发货
      await api.request({ id: p.id }, "orderStock/send");
      p.sendTime = parseInt(new Date().getTime() / 1000);
      return;
    } else if (type == 6) { // 确认收货
      await api.request({ id: p.id }, "orderStock/recv");
      p.recvTime = parseInt(new Date().getTime() / 1000);
      return;
    }
    entity.value?.open(type as gt.curd, p, props.type);
  }
  function rowClass({ row }: { row: gt.sql.orderStock; }) {
    return row && row.redress && props.type != "消费单" ? (row.redress == "-" ? "blueRow" : "redRow") : "";
  }

  function fh(row: gt.sql.orderStock) {
    return row.sendTime < 1 && (api.me.per("强制发货") || row.create == api.mid || row.outGid == api.me.gid);
  }
  function sh(row: gt.sql.orderStock) {
    return row.recvTime < 1 && (api.me.per("强制收货") || row.inGid == api.me.gid);
  }
</script>
<template>
  <div class="List y whf">
    <Filter :data="filterData" isRow class="mb1em" />
    <el-table stripe highlight-current-row :data="page.data" class="wf fg1" type="expand" row-key="id"
      :rowClassName="rowClass">
      <el-table-column prop="id" label="id" width="100" show-overflow-tooltip />
      <el-table-column prop="_createTime" label="创建时间" width="120" show-overflow-tooltip />
      <el-table-column prop="createName" label="创建人" width="120" show-overflow-tooltip />
      <el-table-column prop="inGidName" label="入库商家" width="100" show-overflow-tooltip />
      <el-table-column prop="outGidName" label="出库商家" width="100" show-overflow-tooltip />
      <el-table-column prop="name" label="名称" show-overflow-tooltip />
      <el-table-column prop="des" label="备注" show-overflow-tooltip />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <div class="buttons x zb">
            <template v-for="a in tip">
              <el-tooltip v-if="a.per" :content="a.label">
                <div :class="a.cls" @click.stop="click(a.value, row)" />
              </el-tooltip>
            </template>
            <template v-if="fh(row)">
              <el-tooltip content="确认发货">
                <div class="mac-ico-salesinvoice" @click.stop="click(5, row)" />
              </el-tooltip>
            </template>
            <template v-if="sh(row)">
              <el-tooltip content="确认收货">
                <div class="mac-ico-receipt" @click.stop="click(6, row)" />
              </el-tooltip>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="prev, pager, next, jumper, ->, sizes, total"
      :page-sizes="[10, 20, 30, 40, 50, 100]" v-model:page-size="page.size" :total="page.total"
      v-model:currentPage="page.current" @size-change="init" @current-change="init" />
    <Dialog @confirm="init" ref="entity" />
  </div>
</template>
<style lang="scss">
  .List {
    position: relative;
    .buttons {
      >div {
        cursor: pointer;
        padding: 0 0.4em;
        font-weight: 600;
        &:hover {
          border: 1px solid #a5a5a5;
          box-sizing: border-box;
          border-radius: 0.5em;
          box-shadow: 0 0 10px #000;
        }
      }
      >.mac-ico-add-round {
        color: var(--color-success);
      }
      >.mac-ico-edit {
        color: var(--color-warning);
      }
      >.mac-ico-search {
        color: var(--color-primary);
      }
      >.mac-ico-delete {
        color: var(--color-error);
      }
      >.mac-ico-salesinvoice {
        color: var(--color-success);
      }
      >.mac-ico-receipt {
        color: var(--color-error);
      }
    }
    .el-table {

      .blueRow {
        color: blue;
      }
      .redRow {
        color: red;
      }
    }
  }
</style>